import axios from 'axios'

class HttpRequest {
  constructor() {
    this.baseUrl = ''
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      },
      withCredentials: true
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      if (config.method === 'get') {
        // config.params = qs.stringify(config.params)
      } else {
        config.headers = {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      }
      // console.log(config);
      this.queue[url] = true
      // console.log(config);
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // console.log(res);
      this.destroy(url)
      const { data, status } = res
      if (status !== 200) {
        alert(res.error)
      }
      return data
      // return { result, status }
    }, error => {
      this.destroy(url)
      console.log('===========')
      console.log(JSON.parse(JSON.stringify(error)))

      return Promise.reject(error)
    })
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
  getBase() {
    return axios
  }
}
export default HttpRequest
